package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.Result;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;


//    新增菜品，同时保存对应的口味数据
    @PostMapping
    public Result<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.saveWithFlaVor(dishDto);
//        清理某个分类下的菜品缓存数据
        String key="dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return Result.success("保存成功");
    }

//菜品信息的分页,但有分类表里的数据
    @GetMapping("/page")
    public Result<Page> page(Integer page,Integer pageSize,String name){
//        先把Dish和DishDto两张表的分页new出来
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
//        只查询Dish的分页，但是没有菜品分类这条信息
        LambdaQueryWrapper<Dish> lqw=new LambdaQueryWrapper<>();
        lqw.like(name!=null,Dish::getName,name);
        lqw.orderByDesc(Dish::getUpdateTime);
        dishService.page(pageInfo,lqw);
//         除了records这一个属性两个分页不同,其他的都一样,先把pageInfo的数据导进dishDtoPage
//         records这个属性就是List<>数组,表示分页里面的每条信息
//         里面有菜品分类信息,下面只要对dishDtoPage里面的属性赋值然后再set回去就行了
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list=new ArrayList<>();
        for (Dish record : records) {
            DishDto dishDto=new DishDto();
//            先赋dish里面的属性值
            BeanUtils.copyProperties(record,dishDto);
//            再把dish里面没有的菜品分类这条数据加上
            Long categoryId = record.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if(category!=null){
                dishDto.setCategoryName(category.getName());
                list.add(dishDto);
            }
        }
//        最后set
        dishDtoPage.setRecords(list);
        return Result.success(dishDtoPage);
    }

//    根据菜品id查询菜品信息和对应的口味信息
    @GetMapping("/{id}")
    public Result<DishDto> get(@PathVariable Long id){
        DishDto dishDto=dishService.getByIdWithFlavor(id);
        return Result.success(dishDto);
    }

//    修改菜品和对应的口味信息
    @PutMapping
    public Result<String> updateWithFlavor(@RequestBody DishDto dishDto){

        dishService.updateWithFlavor(dishDto);
//        清理某个分类下的菜品缓存数据
        String key="dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return Result.success("修改成功");
    }

//    删除菜品和口味信息
    @DeleteMapping
    public Result<String> deleteWithFlavor(@RequestParam List<Long> ids){
        log.info("要删除的数据：{}",ids);
        dishService.deleteWithFlavor(ids);
        return Result.success("删除成功");
    }

//    菜品起售和停售
    @PostMapping("/status/{status}")
    public Result<String> updateStatus(@PathVariable Integer status,@RequestParam List<Long> ids){
        for (Long id : ids) {
            Dish dish = dishService.getById(id);
            dish.setStatus(status);
            dishService.updateById(dish);
        }
        return Result.success("售卖状态修改成功");
    }

//    在新增套餐中用于展示每个category对应的菜品种类
//    查询category对应的菜品种类
//    移动端页面要显示Flavor，返回了DishDto增加了口味数据
    @GetMapping("/list")
    public Result<List<DishDto>> selectByCategoryId(Long categoryId){
//先根据categoryId的不同自定义每次菜品查询都不一样的key
        List<DishDto> list=null;
        String key="dish_"+categoryId+"_1";
//先从Redid中获取缓存数据
        list = (List<DishDto>)redisTemplate.opsForValue().get(key);
        if(list!=null){
//        如果有缓存，直接返回
            return Result.success(list);
        }

        LambdaQueryWrapper<Dish> lqw=new LambdaQueryWrapper<>();
        lqw.eq(Dish::getCategoryId,categoryId);
//        只有起售的套餐查的出来
        lqw.eq(Dish::getStatus,1);
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list1 = dishService.list(lqw);
        list=new ArrayList<>();
        for (Dish dish : list1) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish,dishDto);
            LambdaQueryWrapper<DishFlavor> lqw1=new LambdaQueryWrapper<>();
            lqw1.eq(DishFlavor::getDishId,dish.getId());
            List<DishFlavor> flavor = dishFlavorService.list(lqw1);
            dishDto.setFlavors(flavor);
            list.add(dishDto);
        }
//        没有缓存数据，则在查询数据库之后把数据缓存到Redis
        redisTemplate.opsForValue().set(key,list,1L, TimeUnit.HOURS);
        return Result.success(list);
    }
}
